package ls.controller;

import ls.model.Moaning;
import ls.model.Reply;
import ls.model.Vote;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import ls.model.Choice;

@Controller
@RequestMapping("/vote")
public class VotingController extends BaseController {
    protected static final int REPLIES_COUNT = 2;
    protected static final String ATTR_VOTE = "vote";
    protected static final String JSP_VOTE = "vote";

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView getMoaningToVote(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(JSP_VOTE);
        Moaning moaning = getMoaningRepository().getRandomMoaning(REPLIES_COUNT);
        request.getSession().setAttribute(ATTR_MOANING, moaning);
        view.addObject(ATTR_MOANING, moaning);
        view.addObject(ATTR_REPLIES, moaning.getReplies());
        view.addObject(ATTR_VOTE, new Vote());
        view.addObject(ATTR_READ_ONLY, false);
        return view;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView postVote(List<Long> replyIds, HttpServletRequest request) {
        Moaning moaning = (Moaning) request.getSession().getAttribute(ATTR_MOANING);
        request.getSession().removeAttribute(ATTR_MOANING);
        Vote vote = new Vote();
        vote.setMoaning(moaning);
        for (int i = 0; i < replyIds.size(); i++) {
            vote.getChoices().add(new Choice(i, 
                    getMoaningRepository().getReply(replyIds.get(i))));
        }
        getMoaningRepository().addVote(moaning.getId(), vote);

        ModelAndView view = new ModelAndView(JSP_VOTE);
        view.addObject(ATTR_MOANING, moaning);

        List<Reply> reorderedReplies = new ArrayList<Reply>();
        for (Choice choice: vote.getChoices()) {
            reorderedReplies.add(choice.getReply());
        }
        view.addObject(ATTR_REPLIES, reorderedReplies);
        view.addObject(ATTR_READ_ONLY, true);
        return view;
    }
}


